package edu.uba.fcen.estimacion.word.selection.command;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.uba.fcen.estimacion.word.selection.constants.Constants;

public class ReplaceWord {

	private static String fileToReplace = "/Users/matias2681/Documents/facultad/tesis/wikipedia/words/changed";
	private static String fileToRead = "/Users/matias2681/Documents/facultad/tesis/wikipedia/words/words.txt";
	
	public static void main(String[] args) {
		String wordToSearch = args[0];
		String wordToReplace = "#" + wordToSearch;
		try {
			Reader in = new InputStreamReader(new FileInputStream(fileToRead), Constants.ENCODING);
			BufferedReader br = new BufferedReader(in);
			OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(
					fileToReplace),
					Constants.ENCODING);
			BufferedWriter writer = new BufferedWriter(out);
			String line;
			Pattern patternForWord = Pattern.compile("\\b"+wordToSearch+"\\b", Pattern.UNICODE_CASE);
			Matcher match;
			while((line = br.readLine()) != null) {
				match = patternForWord.matcher(line);
				if (match.find()) {
					writer.write(match.replaceAll(wordToReplace));
				} else {
					writer.write(line);
				}
				writer.write(System.getProperty("line.separator"));
			}
			writer.flush();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
